#include "ThreadPool.h"

int loginFunc(int netfd,char* name,MYSQL* mysql){
    int usererror=2;
    int passwderror=1;
    int right=0;

    char username[128]={0};
    char passwd[4096]={0};
    char salt[10]={0};

    char sql[4096]={0};

    int times=3;
    int name_length=0;
    int passwd_length=0;

    while(1){

        bzero(username,sizeof(username));
        bzero(passwd,sizeof(passwd));
        bzero(sql,sizeof(sql));

        if(times==0){
            return -1;
        }

        recvn(netfd,&name_length,sizeof(int));
        recvn(netfd,username,name_length);

        recvn(netfd,&passwd_length,sizeof(int));
        recvn(netfd,passwd,passwd_length);

        sprintf(sql,"select * from info where username='%s';",username);
        int ret=mysql_query(mysql,sql);
        MYSQL_QUERY_CHECK(ret,mysql);

        MYSQL_RES* result=mysql_store_result(mysql);
        MYSQL_ROW row=mysql_fetch_row(result);

        if(row==NULL){
            //说明没有用户
            send(netfd,&usererror,sizeof(int),MSG_NOSIGNAL);
            continue;
        }
        memcpy(salt,row[2],strlen(row[2]));
        char* crypasswd=crypt(passwd,salt);
        if(strcmp(crypasswd,row[3])==0){
            send(netfd,&right,sizeof(int),0);
            memcpy(name,username,strlen(username));
            mysql_free_result(result);
            return 0;
        }
        else{
            send(netfd,&passwderror,sizeof(int),MSG_NOSIGNAL);
            times--;
            mysql_free_result(result);
            continue;
        }
    }
    return -1;
}

int getCurFolder(char* username,MYSQL* mysql){
    char sql[4096]={0};
    sprintf(sql,"select * from virtual_file where name='/'and user='%s' and tomb=0;",username);
    int ret=mysql_query(mysql,sql);
    MYSQL_QUERY_CHECK(ret,mysql);

    MYSQL_RES* result=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(result);
    int retval;
    if(row==NULL){
        mysql_free_result(result);
        return -1;
    }
    else{
        retval=atoi(row[0]);
        mysql_free_result(result);
        return retval;
    }
}
